/**
 * 
 */
package org.bankabeule.ui.actions;

import java.io.File;
import java.util.Collections;

import org.bankabeule.BankabeuleFactory;
import org.bankabeule.Model;
import org.bankabeule.core.ModelManager;
import org.bankabeule.ui.Activator;
import org.bankabeule.ui.utils.Logger;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;

/**
 * @author sdudoit
 *
 */
public class NewAction extends Action {

	
	public NewAction() {
		super();
		setText("&New");
		setId(getClass().getCanonicalName());
		setImageDescriptor(Activator.getImageDescriptor("NewFile.gif"));
	}
	
	
	@Override
	public void run() {
		try {
			FileDialog dialog = new FileDialog(Display.getCurrent()
					.getActiveShell(), org.eclipse.swt.SWT.SAVE);
			dialog.setFilterExtensions(new String[]{ModelManager.FILE_EXTENSION});
			String path = dialog.open();
			if (path != null) {
				if (!path.endsWith("." + ModelManager.FILE_EXTENSION)) {
					path = path + "." + ModelManager.FILE_EXTENSION;
				}
				// check path
				File testFile = new File(path);
				if (testFile.exists()) {
					MessageDialog.openError(Display.getCurrent()
					.getActiveShell(), "Error", "File already exists.");
					run();
				} else {
					URI fileURI = URI.createFileURI(path);
					ResourceSet resourceSet = new ResourceSetImpl();
					Resource resource = resourceSet.createResource(fileURI);
					Model model = BankabeuleFactory.eINSTANCE.createModel();
					resource.getContents().add(model);
					resource.save(Collections.EMPTY_MAP);
					if (ModelManager.get().isDirty()) {
						boolean mustSave = MessageDialog.openConfirm(Display.getCurrent().getActiveShell(), 
								"Confirmation", "Do you want to save before closing ?");
						if (mustSave) {
							ModelManager.get().save();
						}
					}
					ModelManager.get().load(path);
				}
			}
			//WizardDialog dialog = new WizardDialog(Display.getCurrent().getActiveShell(), new AccountWizard());
			//dialog.open();
		} catch (Exception e) {
			Logger.log(e);
		}
	}

	
}
